package com.py.custom.ability.threadpool;

import com.py.custom.ability.threadpool.metric.PoolConfig;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * description：线程池使用类
 */
public class ExecutorServices {

    public static volatile boolean open = false;

    private static final Map<String, NamedThreadPoolExecutor> EXECUTOR_SERVICE_MAP = new ConcurrentHashMap<>();

    public static ExecutorService poolFromName(String poolName) {
        NamedThreadPoolExecutor executorService = EXECUTOR_SERVICE_MAP.get(poolName);
        if (Objects.nonNull(executorService)) {
            System.out.println("---max pool size:--" + executorService.getMaximumPoolSize());
            return executorService;
        } else {
            PoolConfig config = new PoolConfig();
            config.setCorePoolSize(2);
            config.setMaximumPoolSize(5);
            config.setKeepAliveTime(10);
            config.setUnit(TimeUnit.SECONDS);
            config.setWorkQueue(new ArrayBlockingQueue<Runnable>(10));
            config.setThreadFactory(new NamedThreadFactory(poolName));

            config.setHandler(new ThreadPoolExecutor.AbortPolicy());

            NamedThreadPoolExecutor executor = new NamedThreadPoolExecutor(config);
            EXECUTOR_SERVICE_MAP.put(poolName, executor);
            Thread thread = new Thread(() -> {
                System.out.println("================1");
                while (true) {
                    if (open) {
                        executor.setMaximumPoolSize(20);
                        break;
                    }
                }
                System.out.println("================2");
            });
            thread.start();
            return executor;
        }
    }

}
